package com.jinghangzz.shop.head.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinghangzz.shop.common.controller.BaseController;
import com.jinghangzz.shop.common.util.ConstatFinalUtil;
import com.jinghangzz.shop.common.util.PageInfoUtil;
import com.jinghangzz.shop.goods.pojo.AGoods;
import com.jinghangzz.shop.goods.pojo.AGoodsCate;
import com.jinghangzz.shop.goods.service.IGoodsOperService;
import com.jinghangzz.shop.goods.service.IGoodsService;
import com.jinghangzz.shop.users.pojo.AUsers;
import com.jinghangzz.shop.users.pojo.AUsersCar;
import com.jinghangzz.shop.users.service.IUsersService;

/**
 * 前台的Controller
 * @author TeaBig
 */
@Controller
@RequestMapping("/")
public class MainHeadController extends BaseController
{
	@Resource
	private IGoodsService goodsService;
	@Resource
	private IGoodsOperService goodsOperService;
	@Resource
	private IUsersService usersService;
	
	/**
	 * 首页
	 * @return
	 */
	@RequestMapping("/main")
	public String main()
	{
		ConstatFinalUtil.SYS_LOGGER.info("====main====");
		return "/head/main";
	}
	
	/**
	 * 商品列表
	 * @return
	 */
	@RequestMapping("/goods")
	public String goods(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("====goods====");
		/* 搜索条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 准备搜索条件 */
		proccedSearchCond(request, condMap);
		/* 生成分页工具类放到单独的一个方法中 */
		PageInfoUtil pageInfoUtil = proccedPageInfoUtil(request);
		pageInfoUtil.setPageSize(6);
		/* 只能查询启用的商品 */
		condMap.put("status", "1");
		
		/*-------处理额外的搜索条件---------*/
		/* 接收参数 */
		String cateId = request.getParameter("cateId");
		/* 把参数再放到request中 */
		request.setAttribute("cateId", cateId);
		
		/* ----------写死的-------- */
		condMap.put("cateId", cateId);
		
		/* 查询多条记录 */
		List<AGoods> goodsList = this.goodsService.findCondListGoodsService(pageInfoUtil,condMap);
		
		/* 因为Controller要跳转到jsp上面,
		 * 得需要把List放到request中 */
		model.addAttribute("goodsList", goodsList);
		model.addAttribute("pageInfoUtil", pageInfoUtil);
		return "/head/goods";
	}
	
	/**
	 * 商品列表
	 * @return
	 */
	@RequestMapping("/goods/{url}")
	public String goods(@PathVariable String url,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("====goods=商品详情===");
		/* 搜索条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 只能查询启用的商品 */
		condMap.put("url", url);
		/* 查询数据库 */
		AGoods goods = this.goodsService.findOneGoodsService(condMap);
		/* 存储到request中 */
		model.addAttribute("goods", goods);
		return "/head/goodsInfo";
	}
	
	/**
	 * 网页头
	 * @return
	 */
	@RequestMapping("/header")
	public String header(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("====header====");
		/* 搜索条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 查询所有的商品分类(启用的) */
		condMap.clear();
		//condMap.put("status","1");
		//List<AGoodsCate> cateList = this.goodsService.findCondListGoodsCateService(null, condMap);
		List<AGoodsCate> cateList = this.goodsOperService.findListCateTreeService(null);
		/* 把品牌放到request中 */
		model.addAttribute("cateList", cateList);
		return "/head/header";
	}
	
	/**
	 * 购物车列表
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/cart")
	public String cart(HttpServletRequest request,Model model) throws Exception
	{
		ConstatFinalUtil.SYS_LOGGER.info("==cart==");
		/*登陆后读取数据库
		 * 登陆前读取Cookie
		 * */
		HttpSession session = request.getSession() ; 
		AUsers usersSess = (AUsers) session.getAttribute("users");
		if(usersSess != null)
		{
			/* 登陆了 */
			/* 查询数据库
			 * 是根据usersId查询
			 *  */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("usersId", usersSess.getId());
			List<AUsersCar> usersCarList = this.usersService.findCondListUsersCarService(null, condMap);
			/* 存储到request中 */
			model.addAttribute("usersCarList", usersCarList);
		}else
		{
			/* 未登陆,从Cookie中读取 */
			cartCookieList(request, model);
		}
		return "/head/cart";
	}

	/**
	 * 从Cookie中读取购物车
	 * @param request
	 * @param model
	 * @throws UnsupportedEncodingException
	 */
	private void cartCookieList(HttpServletRequest request, Model model) throws UnsupportedEncodingException
	{
		/*--从Cookie中获取数据---*/
		/* 键 */
		String name = "goodsList";
		/* 只要看到值可以存储字符串的时候,统一使用JSON
[
	{"gid":"","num":""},
	{"gid":"","num":""},
	{"gid":"","num":""},
]
		 *  */
		String value = "" ; 
		
		boolean cookieFlag = false; 
		/* 获取Cookie */
		Cookie[] cookieReq = request.getCookies();
		if(cookieReq != null)
		{
			for (int i = 0; i < cookieReq.length; i++)
			{
				Cookie cookieTemp = cookieReq[i];
				String nameTemp = cookieTemp.getName() ; 
				String valTemp = cookieTemp.getValue() ; 
				if(nameTemp.equalsIgnoreCase(name))
				{
					/* 得找我们当时存储的名字 */
					value = URLDecoder.decode(valTemp,"UTF-8");
					cookieFlag = true ; 
					break ; 
				}
			}
		}
		
		JSONArray goodsListArr = new JSONArray();
		if(cookieFlag)
		{
			/* 购物车有数据库 */
			goodsListArr = JSON.parseArray(value);
			if(goodsListArr == null)
			{
				goodsListArr = new JSONArray();
			}
		}
		
		/* 最终:需要把cookie中的数据变成List,这里面放的是AUsersCar */
		List<AUsersCar> usersCarList = new ArrayList<AUsersCar>();
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 一边循环goodsListArr,一边往usersCarList中放东西 */
		for (Iterator iterator = goodsListArr.iterator(); iterator.hasNext();)
		{
			JSONObject goodsTempJSON = (JSONObject) iterator.next();
			String goodsId = goodsTempJSON.getString("gid");
			String num = goodsTempJSON.getString("num");
			
			AUsersCar usersCar = new AUsersCar();
			usersCar.setGoodsId(Integer.valueOf(goodsId));
			usersCar.setNum(Integer.valueOf(num));
			
			usersCar.setStatus(Byte.valueOf("1"));
			usersCar.setCreateTime(new Date());
			usersCar.setUpdateTime(new Date());
			usersCar.setPubTime(new Date());
			
			/* 查询商品 ;根据商品Id查询*/
			condMap.clear();
			condMap.put("id", usersCar.getGoodsId());
			AGoods goods = this.goodsService.findOneGoodsService(condMap);
			usersCar.setGoods(goods);
			
			usersCarList.add(usersCar);
		}
		/* 存储购物车 */
		model.addAttribute("usersCarList", usersCarList);
	}
	
	/**
	 * 购物车
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/cartInsert")
	public String cartInsert(HttpServletRequest request,HttpServletResponse response,Model model) throws Exception
	{
		ConstatFinalUtil.SYS_LOGGER.info("==cartInsert==");
		/*登陆后读取数据库
		 * 登陆前读取Cookie
		 * */
		HttpSession session = request.getSession() ; 
		AUsers usersSess = (AUsers) session.getAttribute("users");
		if(usersSess != null)
		{
			String goodsId = request.getParameter("goodsId");
			String num = request.getParameter("num");
			
			AUsersCar usersCar = new AUsersCar();
			usersCar.setUsersId(usersSess.getId());
			
			usersCar.setGoodsId(Integer.valueOf(goodsId));
			usersCar.setNum(Integer.valueOf(num));
			usersCar.setStatus(Byte.valueOf("1"));
			usersCar.setCreateTime(new Date());
			usersCar.setUpdateTime(new Date());
			usersCar.setPubTime(new Date());
			/* 存储数据库 */
			JSONObject resultJSON = this.usersService.saveOneUsersCarService(usersCar);
			ConstatFinalUtil.SYS_LOGGER.info("购物车存储数据库结果:{}",resultJSON.toJSONString());
		}else
		{
			/* 未登陆,从Cookie中读取 */
			cartCookieInsert(request, response);
		}
		
		/* 如果添加成功,会跳转到购物车列表页面 */
//		String carStr = this.cart(request, model);
//		return carStr ; 
		return "redirect:/cart.htm" ; 
	}

	/**
	 * 操作Cookie
	 * @param request
	 * @param response
	 * @throws UnsupportedEncodingException
	 */
	private void cartCookieInsert(HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException
	{
		/* 键 */
		String name = "goodsList";
		/* 只要看到值可以存储字符串的时候,统一使用JSON
[
	{"gid":"","num":""},
	{"gid":"","num":""},
	{"gid":"","num":""},
]
		 *  */
		String value = "" ; 
		
		boolean cookieFlag = false; 
		/* 获取Cookie */
		Cookie[] cookieReq = request.getCookies();
		if(cookieReq != null)
		{
			for (int i = 0; i < cookieReq.length; i++)
			{
				Cookie cookieTemp = cookieReq[i];
				String nameTemp = cookieTemp.getName() ; 
				String valTemp = cookieTemp.getValue() ; 
				if(nameTemp.equalsIgnoreCase(name))
				{
					/* 得找我们当时存储的名字 */
					value = URLDecoder.decode(valTemp,"UTF-8");
					cookieFlag = true ; 
					break ; 
				}
			}
		}
		
		/* 商品Id */
		String goodsId = request.getParameter("goodsId");
		String num = request.getParameter("num");
		
		/* 商品的数据 */
		JSONArray goodsListArr = new JSONArray();
		if(cookieFlag)
		{
			/* 从原来的Cookie中找到了 */
			goodsListArr = JSON.parseArray(value);
			if(goodsListArr == null)
			{
				goodsListArr = new JSONArray();
			}
		}
		
		/* 增加一个商品 */
		JSONObject goodsJSON = new JSONObject();
		goodsJSON.put("gid", goodsId);
		goodsJSON.put("num", num);
		
		/* 断言:假设
		 * 假设不存在 
		 *  */
		boolean exitsFlag = false ; 
		/* 数量累加如何实现
		 * 判断商品id是否已经添加过
		 *  */
		for (Iterator iterator = goodsListArr.iterator(); iterator.hasNext();)
		{
			JSONObject goodsTempJSON = (JSONObject) iterator.next() ;
			String gid = goodsTempJSON.getString("gid");
			String numOld = goodsTempJSON.getString("num");
			if(gid.equalsIgnoreCase(goodsId))
			{
				/* 商品id一样,存在重复 */
				/*
				 * 3 :字符串
				 * 5 :字符串
				 * 3 + 5 = 35 ; (字符串)
				 * 3 + 5 = 8 ;(整数类型) 
				 * */
				num = Integer.valueOf(num) + Integer.valueOf(numOld) + ""; 
				goodsTempJSON.put("num", num);
				//goodsListArr.add(goodsTempJSON) ; 
				/* 说明存在了 */
				exitsFlag = true ; 
				break ; 
			}
		}
		
		if(!exitsFlag)
		{
			goodsListArr.add(goodsJSON);
		}
		/* 重新赋值 */
		value = URLEncoder.encode(goodsListArr.toJSONString(),"UTF-8") ; 
		/* 准备一个Cookie */
		Cookie goodsListCookie = new Cookie(name, value);
		/* 对Cookie做一些设置 */
		goodsListCookie.setPath(request.getContextPath());
		/* 存储一周 */
		goodsListCookie.setMaxAge(60 * 60 * 24 * 7);
		goodsListCookie.setComment("goodsList");
		ConstatFinalUtil.SYS_LOGGER.info("cookie:{},name:{},value:{}",goodsListCookie,name,value);
		/* 把Cookie添加到浏览器中 */
		response.addCookie(goodsListCookie);
	}
	
	/**
	 * 清空购物车
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/cleanAll")
	public String cleanAll(HttpServletRequest request,HttpServletResponse response,Model model) throws Exception
	{
		ConstatFinalUtil.SYS_LOGGER.info("==cartInsert==");
		/* 键 */
		String name = "goodsList";
		/* 只要看到值可以存储字符串的时候,统一使用JSON
[
	{"gid":"","num":""},
	{"gid":"","num":""},
	{"gid":"","num":""},
]
		 *  */
		String value = "" ; 
		
		/* 准备一个Cookie */
		Cookie goodsListCookie = new Cookie(name, value);
		/* 对Cookie做一些设置 */
		goodsListCookie.setPath(request.getContextPath());
		/* 存储一周 */
		goodsListCookie.setMaxAge(60 * 60 * 24 * 7);
		goodsListCookie.setComment("goodsList");
		ConstatFinalUtil.SYS_LOGGER.info("cookie:{},name:{},value:{}",goodsListCookie,name,value);
		/* 把Cookie添加到浏览器中 */
		response.addCookie(goodsListCookie);
		
		/* 如果添加成功,会跳转到购物车列表页面 */
//		String carStr = this.cart(request, model);
//		return carStr ; 
		return "redirect:/cart.htm" ; 
	}
}
